package tongwentongshu.com.app.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.imsdk.ext.sns.TIMAddFriendRequest;
import com.tencent.imsdk.ext.sns.TIMFriendResult;
import com.tencent.imsdk.ext.sns.TIMFriendshipManagerExt;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import tongwentongshu.com.app.R;
import tongwentongshu.com.app.activityim.ChatActivity;
import tongwentongshu.com.app.activityim.HomeActivity;
import tongwentongshu.com.app.bean.AppItem;
import tongwentongshu.com.app.bean.OrderEvent;
import tongwentongshu.com.app.bean.PersonalBean;
import tongwentongshu.com.app.bean.SumEvent;
import tongwentongshu.com.app.contract.CallBackColonyContract;
import tongwentongshu.com.app.contract.PersonalHomePageContract;
import tongwentongshu.com.app.db.Cache;
import tongwentongshu.com.app.fragment.BaseFragmentActivity;
import tongwentongshu.com.app.fragment.MyReadingFragment;
import tongwentongshu.com.app.fragment.PerReadingFragment;
import tongwentongshu.com.app.fragment.PerShareFragment;
import tongwentongshu.com.app.presenter.PersonalHomePagePresenter;
import tongwentongshu.com.app.utils.GlideUtil;
import tongwentongshu.com.app.utils.NetUtils;

/**
 * Created by XiongBin on 2017/7/10.
 */

public class PersonalHomePageActivity extends BaseFragmentActivity implements PersonalHomePageContract.View {
    @BindView(R.id.tv_reading_sum)
    TextView readingSum;
    @BindView(R.id.tv_share_sum)
    TextView shareSum;

    @BindView(R.id.tv_me_head)
    ImageView userPic;//头像
    @BindView(R.id.tv_user_name)
    TextView userName;//姓名
    @BindView(R.id.tv_sex)
    TextView userSex;//性别
    @BindView(R.id.tv_auth)
    TextView userAuth;//认证状态
    @BindView(R.id.tv_msg)
    TextView msg;//聊天
    @BindView(R.id.tv_follow)
    TextView follow;//关注
    @BindView(R.id.ll_)
    LinearLayout ll;//布局
    @BindView(R.id.iv_sex)
    ImageView userSexPic;//性别标识

    private PersonalHomePagePresenter personalHomePagePresenter;
    private int item_width;
    /**
     * 主页加载的Fragment
     */
    private ArrayList<Fragment> fragments;
    /**
     * 页面展示ViewPager
     */
    @BindView(R.id.pager)
    ViewPager pager;
    @BindView(R.id.rel_iv_h)
    RelativeLayout h;
    /**
     * 导航底部线条
     */
    @BindView(R.id.iv_line)
    ImageView mImageView;
    /**
     * 导航栏动画相关参数
     */
    private int endPosition;
    private int beginPosition;
    private int currentFragmentIndex;
    private boolean isEnd;

    private String id = "";

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_personal_homepage;
    }

    @Override
    protected int getTitleId() {
        return R.string.personal_homepage;
    }

    @Override
    protected void initView() {
        id = getIntent().getExtras().getString(Cache.USER_ID);
        item_width = (int) ((NetUtils.getDisplayMetrics(this, NetUtils.DM_WIDTH) / 2.0));
        mImageView.getLayoutParams().width = item_width;

    }

    @Override
    protected void initData() {
        personalHomePagePresenter = new PersonalHomePagePresenter(this);
        personalHomePagePresenter.initMyInfo();
    }

    @OnClick({R.id.ll_reading, R.id.ll_share, R.id.tv_msg, R.id.tv_follow})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_reading:
                pager.setCurrentItem(0);
                break;
            case R.id.ll_share:
                pager.setCurrentItem(1);
                break;
            case R.id.tv_msg:
                checkIM(new CallBackColonyContract.OnCheck() {
                    @Override
                    public void check() {
                        initFind();
                    }
                });
                break;
            case R.id.tv_follow:
                personalHomePagePresenter.follow(String.valueOf(bean.getData().getIs_follow()));
                break;
        }
    }

    public void onEventMainThread(SumEvent result) {
        if (TextUtils.isEmpty(result.getShareSum())) {
            readingSum.setText("阅读(" + result.getReadingSum() + ")");
        } else {
            shareSum.setText("分享(" + result.getShareSum() + ")");
        }

    }

    private void initViewPager(String id) {
        fragments = new ArrayList<Fragment>();
        Bundle data = new Bundle();
        data.putString(Cache.USER_ID, id);

        PerReadingFragment fragment1 = new PerReadingFragment(this);
        fragment1.setArguments(data);
        fragments.add(fragment1);
        PerShareFragment fragment2 = new PerShareFragment(this);
        fragment2.setArguments(data);
        fragments.add(fragment2);
        MyFragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(
                getSupportFragmentManager(), fragments);
        fragmentPagerAdapter.setFragments(fragments);
        pager.setAdapter(fragmentPagerAdapter);
        pager.setOnPageChangeListener(new MyOnPageChangeListener());
        pager.setCurrentItem(0);
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public String getFollowId() {
        return id;
    }

    @Override
    public String getPhone() {
        return getIntent().getExtras().getString("phone");
    }

    PersonalBean bean;

    @Override
    public void onSuccess(PersonalBean msg) {
        this.bean = msg;
        userName.setText(msg.getData().getUser_nickname());
        if (msg.getData().getSex().equals("1")) {
            userSex.setText("男");
            userSexPic.setImageResource(R.drawable.mr);
        } else if (msg.getData().getSex().equals("2")) {
            userSex.setText("女");
            userSexPic.setImageResource(R.drawable.miss);
        } else {
            userSex.setText("保密");
        }
        if (msg.getData().getUser_status().equals("1")) {
            userAuth.setText("已认证");
        } else {
            userAuth.setText("未认证");
        }
        if (msg.getData().getIs_my() == 1) {
            ll.setVisibility(View.GONE);
        } else {
            ll.setVisibility(View.VISIBLE);
        }
        GlideUtil.setImage(mContext, msg.getData().getAvatar(), R.drawable.default_graph, R.drawable.default_graph, userPic);
        initFollow();
        initViewPager(msg.getData().getUser_id());
        Log.e("id", msg.getData().getUser_id());
    }

    void initFollow() {
        if (bean.getData().getIs_follow() == 1) {
            follow.setText("取消关注");
        } else {
            follow.setText("关注");
        }
    }

    @Override
    public void onSuccess(AppItem msg) {
        personalHomePagePresenter.initMyInfo();

    }

    private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
        private ArrayList<Fragment> fragments;
        private FragmentManager fm;

        public MyFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
            this.fm = fm;
        }

        public MyFragmentPagerAdapter(FragmentManager fm,
                                      ArrayList<Fragment> fragments) {
            super(fm);
            this.fm = fm;
            this.fragments = fragments;
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        public void setFragments(ArrayList<Fragment> fragments) {
            if (this.fragments != null) {
                FragmentTransaction ft = fm.beginTransaction();
                for (Fragment f : this.fragments) {
                    ft.remove(f);
                }
                ft.commit();
                ft = null;
                fm.executePendingTransactions();
            }
            this.fragments = fragments;
            notifyDataSetChanged();
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            Object obj = super.instantiateItem(container, position);
            return obj;
        }

    }

    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageSelected(final int position) {
            Animation animation = new TranslateAnimation(endPosition, position
                    * item_width, 0, 0);

            beginPosition = position * item_width;

            currentFragmentIndex = position;
            if (animation != null) {
                animation.setFillAfter(true);
                animation.setDuration(0);
                mImageView.startAnimation(animation);
            }
        }

        @Override
        public void onPageScrolled(int position, float positionOffset,
                                   int positionOffsetPixels) {
            if (!isEnd) {
                if (currentFragmentIndex == position) {
                    endPosition = item_width * currentFragmentIndex
                            + (int) (item_width * positionOffset);
                }
                if (currentFragmentIndex == position + 1) {
                    endPosition = item_width * currentFragmentIndex
                            - (int) (item_width * (1 - positionOffset));
                }

                Animation mAnimation = new TranslateAnimation(beginPosition,
                        endPosition, 0, 0);
                mAnimation.setFillAfter(true);
                mAnimation.setDuration(0);
                mImageView.startAnimation(mAnimation);
                h.invalidate();
                beginPosition = endPosition;
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if (state == ViewPager.SCROLL_STATE_DRAGGING) {
                isEnd = false;
            } else if (state == ViewPager.SCROLL_STATE_SETTLING) {
                isEnd = true;
                beginPosition = currentFragmentIndex * item_width;
                if (pager.getCurrentItem() == currentFragmentIndex) {
                    // 未跳入下一个页面
                    mImageView.clearAnimation();
                    Animation animation = null;
                    // 恢复位置
                    animation = new TranslateAnimation(endPosition,
                            currentFragmentIndex * item_width, 0, 0);
                    animation.setFillAfter(true);
                    animation.setDuration(1);
                    mImageView.startAnimation(animation);
                    h.invalidate();
                    endPosition = currentFragmentIndex * item_width;
                }
            }
        }

    }

    void initFind() {
//        ChatActivity.navToChat(mContext, bean.getData().getMobile(), TIMConversationType.C2C);
        //创建请求列表
        List<TIMAddFriendRequest> reqList = new ArrayList<TIMAddFriendRequest>();

        //添加好友请求
        TIMAddFriendRequest req = new TIMAddFriendRequest(bean.getData().getMobile());
        req.setAddrSource("AddSource_Type_Android");
        req.setRemark(bean.getData().getUser_nickname());
//        req.set

        reqList.add(req);

        //申请添加好友
        TIMFriendshipManagerExt.getInstance().addFriend(reqList, new TIMValueCallBack<List<TIMFriendResult>>() {
            @Override
            public void onError(int code, String desc) {
                //错误码code和错误描述desc，可用于定位请求失败原因
                //错误码code列表请参见错误码表
                Log.e(TAG, "addFriend failed: " + code + " desc" + desc);
            }

            @Override
            public void onSuccess(List<TIMFriendResult> result) {
                Log.e(TAG, "addFriend succ");

                boolean b = false;
                for (TIMFriendResult res : result) {
                    b = true;
//                    Log.e(TAG, "identifier: " + res.getIdentifer() + " status: " + res.getStatus());

                }
                if (b) {
                    List<String> users = new ArrayList<String>();
                    users.add(bean.getData().getMobile());
                    //获取好友资料
                    TIMFriendshipManager.getInstance().getUsersProfile(users, new TIMValueCallBack<List<TIMUserProfile>>() {
                        @Override
                        public void onError(int code, String desc) {
                            //错误码code和错误描述desc，可用于定位请求失败原因
                            //错误码code列表请参见错误码表
                            Log.e("shi", "getFriendsProfile failed: " + code + " desc");
                        }

                        @Override
                        public void onSuccess(List<TIMUserProfile> result) {

                            String name = result.get(0).getNickName().isEmpty() ? result.get(0).getIdentifier() : result.get(0).getNickName();

                            String imageUrl = result.get(0).getFaceUrl().isEmpty() ? "" : result.get(0).getFaceUrl();

                            ChatActivity.navToChat(mContext, bean.getData().getMobile(), TIMConversationType.C2C, imageUrl, name);
                        }
                    });
                } else {

                }
            }
        });

    }
}
